import {
    ArgumentsHost,
    Catch,
    ExceptionFilter,
    HttpException,
    HttpStatus,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Log } from '@/modules/system/log/entities/log.entity';
import { Repository } from 'typeorm';
import { argumentsToString } from '@/common/utils/common';
// 引入 Fastify 响应类型（关键：明确类型，避免 API 误用）
import { FastifyReply } from 'fastify';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
    constructor(
      @InjectRepository(Log)
      private readonly logRepository: Repository<Log>,
    ) {
    }

    async catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const request = ctx.getRequest();
        // 明确指定响应对象为 FastifyReply 类型（获取类型提示）
        const response: FastifyReply = ctx.getResponse();

        const status = exception.getStatus();
        const exceptionResponse: any = exception.getResponse();

        const message = exception.message
          ? exception.message
          : `${status >= 500 ? '服务器错误（Service Error）' : '客户端错误（Client Error）'}`;

        // 保存日志（逻辑不变）
        await this.logRepository.save({
            ip: request.ip,
            userFlag: request?.user?.username || request.headers?.code,
            name: '请求错误',
            method: request.method,
            message: (exceptionResponse?.message || message).toString(),
            arguments: argumentsToString(request),
            status,
            path: request.originalUrl,
            type: 0,
        });

        // 关键修改：Fastify 用 send() 发送 JSON 响应，替代 Express 的 json()
        response
          .status(status)
          .send({  // 这里将 json() 改为 send()
              code: status,
              msg: exceptionResponse?.message || message,
              error: exceptionResponse.error,
          });
    }
}
